package com.ruoyi.ldzlsc.service.Impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ruoyi.common.core.domain.UR;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.PageDomain;
import com.ruoyi.common.core.web.page.TableSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.ldzlsc.service.ScProductInventoryService;
import com.ruoyi.system.api.BasicService;
import com.ruoyi.system.api.InventoryService;
import com.ruoyi.system.api.domain.BasicProduct;

/**
 * 产品库存Service业务层处理
 *
 * @author ldzl
 */
@Service
public class ScProductInventoryServiceImpl implements ScProductInventoryService {

    // 库存充足状态常量
    private static final String STATUS_SUFFICIENT = "sufficient";
    // 库存不足状态常量
    private static final String STATUS_INSUFFICIENT = "insufficient";

    @Autowired
    private BasicService basicService;

    @Autowired
    private InventoryService inventoryService;



    /**
     * 查询所有产品列表（使用BasicProductMapperlist方法）
     *
     * @param basicProduct
     * @return 产品集合
     */
    @Override
    public TableDataInfo listAllProducts(BasicProduct basicProduct) {
        // 从当前请求中获取分页信息
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        // 将分页信息设置到查询条件对象中，准备随远程调用发送
        Map<String, Object> params = basicProduct.getParams();
        if (params == null) {
            params = new HashMap<>();
        }
        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);
        basicProduct.setParams(params);
         return basicService.list(basicProduct);

    }

    /**
     * 查询产品库存状态
     *
     * @param productIds 产品ID列表
     * @return 产品库存状态列表
     */
    @Override
    public List<Map<String, Object>> getProductStockStatus(List<Long> productIds) {
        List<Map<String, Object>> resultList = new ArrayList<>();

        // 遍历产品ID列表，查询每个产品的库存状态
        for (Long productId : productIds) {
            String productCode = null;
            // 1. 根据产品ID查询产品信息以获取产品编码
            BasicProduct queryProduct = new BasicProduct();
            queryProduct.setProduct_id(productId.intValue());
            TableDataInfo productResult = basicService.list(queryProduct);

            // 2. 解析查询结果
            if (productResult != null && productResult.getRows() != null && !productResult.getRows().isEmpty()) {
                Object rawProduct = productResult.getRows().get(0);
                if (rawProduct instanceof Map) {
                    Map<?, ?> productMap = (Map<?, ?>) rawProduct;
                    Object codeObj = productMap.get("product_code");
                    if (codeObj != null) {
                        productCode = codeObj.toString();
                    }
                }
            }

            // 3. 使用获取到的产品编码查询库存
            UR inventoryResult = null;
            if (productCode != null && !productCode.isEmpty()) {
                inventoryResult = inventoryService.viewInventory(productCode);
            }

            // 解析库存结果
            Map<String, Object> productStatus = new HashMap<>();
            productStatus.put("productId", productId);
            productStatus.put("quantity_num", 0);
            productStatus.put("status", STATUS_INSUFFICIENT);

            // 如果查询成功，设置实际值
            if (inventoryResult != null && inventoryResult.isFlag()) {
                // 处理data字段
                Map<String, Object> data = inventoryResult.getData();
                if (data != null && !data.isEmpty()) {
                    // 解析data获取库存数量
                    Integer stockQty = parseStockQty(data);
                    productStatus.put("quantity_num", stockQty);

                    // 根据库存数量判断状态
                    if (stockQty > 0) {
                        productStatus.put("status", STATUS_SUFFICIENT);
                    }
                }

                // 处理dataList字段
                List<Object> dataList = inventoryResult.getDataList();
                if (dataList != null && !dataList.isEmpty()) {
                    // 假设dataList的第一个元素包含库存信息
                    Object firstItem = dataList.get(0);
                    if (firstItem instanceof Map) {
                        Map<String, Object> itemMap = (Map<String, Object>) firstItem;
                        Integer stockQty = parseStockQtyFromMap(itemMap);
                        if (stockQty > 0) {
                            productStatus.put("quantity_num", stockQty);
                            productStatus.put("status", STATUS_SUFFICIENT);
                        }
                    }
                }
            }
            resultList.add(productStatus);
        }

        return resultList;
    }

    /**
     * 解析库存数量
     *
     * @param data InventoryService返回的数据
     * @return 库存数量
     */
    private Integer parseStockQty(Map<String, Object> data) {
        // 按照 "当前库存" -> "queryNum" -> "quantity_num" 的路径解析
        if (data.containsKey("当前库存")) {
            Object warningObj = data.get("当前库存");
            if (warningObj instanceof Map) {
                Map<?, ?> warningMap = (Map<?, ?>) warningObj;
                if (warningMap.containsKey("queryNum")) {
                    Object queryNumObj = warningMap.get("queryNum");
                    if (queryNumObj instanceof Map) {
                        Map<?, ?> queryNumMap = (Map<?, ?>) queryNumObj;
                        if (queryNumMap.containsKey("quantity_num")) {
                            return parseNumber(queryNumMap.get("quantity_num"));
                        }
                    }
                }
            }
        }

        // 兼容旧的或直接的返回格式
        // 尝试从data中获取"库存明细"键
        if (data.containsKey("库存明细")) {
            Object stockDetailObj = data.get("库存明细");
            if (stockDetailObj instanceof Map) {
                Map<String, Object> stockDetail = (Map<String, Object>) stockDetailObj;
                // 优先检查新字段名 quantity_num
                if (stockDetail.containsKey("quantity_num")) {
                    return parseNumber(stockDetail.get("quantity_num"));
                }
                // 兼容旧字段名 quantity
                if (stockDetail.containsKey("quantity")) {
                    return parseNumber(stockDetail.get("quantity"));
                }
            }
        }

        // 如果没有找到"库存明细"键，尝试直接获取stockQty或quantity_num键
        if (data.containsKey("quantity_num")) {
            return parseNumber(data.get("quantity_num"));
        }
        if (data.containsKey("stockQty")) {
            return parseNumber(data.get("stockQty"));
        }
        return 0;
    }

    /**
     * 解析库存数量
     *
     * @param data InventoryService返回的数据
     * @return 库存数量
     */
    private Integer parseStockQtyFromMap(Map<String, Object> data) {
        // 优先检查新字段名 quantity_num
        if (data.containsKey("quantity_num")) {
            return parseNumber(data.get("quantity_num"));
        }
        // 兼容旧字段名 quantity
        if (data.containsKey("quantity")) {
            return parseNumber(data.get("quantity"));
        }
        // 兼容旧字段名 stockQty
        if (data.containsKey("stockQty")) {
            return parseNumber(data.get("stockQty"));
        }
        return 0;
    }
    
    // 提取出的通用数字解析方法
    private Integer parseNumber(Object obj) {
        if (obj == null) return 0;
        if (obj instanceof Integer) {
            return (Integer) obj;
        } else if (obj instanceof Number) {
            return ((Number) obj).intValue();
        } else {
            try {
                return Integer.parseInt(obj.toString());
            } catch (NumberFormatException e) {
                return 0;
            }
        }
    }

    /**
     * 检查产品是否可以直接出库
     *
     * @param productIds 产品ID列表
     * @return 检查结果，true表示可以出库，false表示不能出库
     */
    @Override
    public boolean canProductOutbound(List<Long> productIds) {
        if (productIds == null || productIds.isEmpty()) {
            return false;
        }

        // 获取产品库存状态
        List<Map<String, Object>> stockStatusList = getProductStockStatus(productIds);

        // 检查所有产品是否都可以直接出库
        for (Map<String, Object> status : stockStatusList) {
            String stockStatus = (String) status.get("status");
            if (!STATUS_SUFFICIENT.equals(stockStatus)) {
                return false;
            }
        }

        return true;
    }

    /**
     * 检查产品是否需要生产
     *
     * @param productIds 产品ID列表
     * @return 检查结果，true表示需要生产，false表示不需要生产
     */
    @Override
    public boolean needProductProduction(List<Long> productIds) {
        if (productIds == null || productIds.isEmpty()) {
            return false;
        }

        // 获取产品库存状态
        List<Map<String, Object>> stockStatusList = getProductStockStatus(productIds);

        // 检查是否有产品需要生产
        for (Map<String, Object> status : stockStatusList) {
            String stockStatus = (String) status.get("status");
            if (STATUS_INSUFFICIENT.equals(stockStatus)) {
                return true;
            }
        }

        return false;
    }
    /**
     * 自动生成编号
     *
     * @param enCode 编号
     * @return 生成的编号
     */
    @Override
    public AjaxResult automaticallyNumbers(Long enCode) {
        return basicService.automaticallyNumbers(enCode);
    }

    /**
     * 根据产品ID查询库存数量
     */
    @Override
    public int getProductStockQuantity(Long productId) {
        if (productId == null) {
            return 0;
        }

        try {
            // 1. 根据产品ID查询产品信息以获取产品编码
            BasicProduct queryProduct = new BasicProduct();
            queryProduct.setProduct_id(productId.intValue());
            TableDataInfo productResult = basicService.list(queryProduct);

            String productCode = null;
            if (productResult != null && productResult.getRows() != null && !productResult.getRows().isEmpty()) {
                Object rawProduct = productResult.getRows().get(0);
                if (rawProduct instanceof Map) {
                    Map<?, ?> productMap = (Map<?, ?>) rawProduct;
                    Object codeObj = productMap.get("product_code");
                    if (codeObj != null) {
                        productCode = codeObj.toString();
                    }
                }
            }

            // 2. 使用产品编码查询库存
            if (productCode != null && !productCode.isEmpty()) {
                UR inventoryResult = inventoryService.viewInventory(productCode);
                if (inventoryResult != null && inventoryResult.isFlag()) {
                    Map<String, Object> data = inventoryResult.getData();
                    if (data != null && !data.isEmpty()) {
                        Integer stockQty = parseStockQty(data);
                        return stockQty != null ? stockQty : 0;
                    }
                }
            }
        } catch (Exception e) {
        }

        return 0;
    }

    /**
     * 批量查询产品库存数量
     */
    @Override
    public Map<Long, Integer> getProductStockQuantities(List<Long> productIds) {
        Map<Long, Integer> result = new HashMap<>();

        if (productIds == null || productIds.isEmpty()) {
            return result;
        }

        for (Long productId : productIds) {
            int stockQty = getProductStockQuantity(productId);
            result.put(productId, stockQty);
        }

        return result;
    }
}
